<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>uni-app中websocket的使用 断开重连、心跳机制 | 唐志远の博客</title><meta name="author" content="Ethan.Tzy"><meta name="copyright" content="Ethan.Tzy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="baidu-site-verification" content="codeva-ujex1yc5TZ"><meta name="description" content="心跳机制，也就是客户端间隔一段时间就向服务器发送一条消息，如果服务器收到消息就回复一条信息过来，如果一定时间内没有回复，则表示已经与服务器断开连接了，这个时候就需要进行重连。">
<meta property="og:type" content="article">
<meta property="og:title" content="uni-app中websocket的使用 断开重连、心跳机制">
<meta property="og:url" content="https://fe32.top/articles/soc145ket/index.html">
<meta property="og:site_name" content="唐志远の博客">
<meta property="og:description" content="心跳机制，也就是客户端间隔一段时间就向服务器发送一条消息，如果服务器收到消息就回复一条信息过来，如果一定时间内没有回复，则表示已经与服务器断开连接了，这个时候就需要进行重连。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bu.dusays.com/2022/05/01/626e8da952344.png">
<meta property="article:published_time" content="2021-09-10T11:51:31.000Z">
<meta property="article:modified_time" content="2023-05-17T10:01:12.000Z">
<meta property="article:author" content="Ethan.Tzy">
<meta property="article:tag" content="uni-app">
<meta property="article:tag" content="webSocket">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bu.dusays.com/2022/05/01/626e8da952344.png"><link rel="shortcut icon" href="https://bu.dusays.com/2022/05/17/6283c38e6368f.ico"><link rel="canonical" href="https://fe32.top/articles/soc145ket/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/css/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"KYE9ZA4757","apiKey":"b5a21077c2b61488e5c748ace78c9340","indexName":"blog-tzy1997","hits":{"per_page":10},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":400},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Ethan.Tzy","link":"链接: ","source":"来源: 唐志远の博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-left"},
  source: {
    justifiedGallery: {
      js: 'https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/fjGallery.min.js',
      css: 'https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/css/fjGallery.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: true,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'uni-app中websocket的使用 断开重连、心跳机制',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-05-17 18:01:12'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><style type="text/css">#toggle-sidebar {bottom: 80px;left:100px}</style><link rel="stylesheet" href="/css/swiper-bundle.css"><link rel="stylesheet" href="/css/tzy.css"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/atom.xml" title="唐志远の博客" type="application/atom+xml">
</head><body><div class="modal-connection"><div class="content"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""><div class="p-title"> 【检测到您已屏蔽网站广告】</div><div>为了本站的长期运营，请将本站加入广告拦截器的白名单，感谢您的支持！🌹🌹🌹 <a class="wwads-text" title="开启方法" target="_blank" rel="nofollow" href="https://fe32.top/adsTips/">【查看开启方法】</a></div></div></div><div id="loading-box"><div class="loading-bg"><div class="loader"><div class="loader-square"></div><div class="loader-square"></div><div class="loader-square"></div><div class="loader-square"></div><div class="loader-square"></div><div class="loader-square"></div><div class="loader-square"></div></div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })
// 20230312 add
setTimeout(function(){ preloader.endLoading();}, 5000);

if (true) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" onerror="onerror=null;src='https://bu.dusays.com/2021/03/27/0106da541a922.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">116</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">88</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/" target="_self"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-book"></i><span> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/archives/" target="_self"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page" href="/tags/" target="_self"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page" href="/categories/" target="_self"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/gallery/" target="_self"><i class="fa-fw fas fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page" href="/bangumis/" target="_self"><i class="fa-fw fab fa-youtube"></i><span> 番剧</span></a></li><li><a class="site-page" href="/movies/" target="_self"><i class="fa-fw fa-fw fas fa-clapperboard"></i><span> 电影</span></a></li><li><a class="site-page" href="/books/" target="_self"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page" href="/specialEffects/" target="_self"><i class="fa-fw fa fa-ship"></i><span> 特效</span></a></li><li><a class="site-page" href="/@3.7.1/wallpaper/" target="_blank"><i class="fa-fw fa-fw fas fa-images"></i><span> 壁纸</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-user-group"></i><span> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/comments/" target="_self"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></li><li><a class="site-page" href="/frdcenter/" target="_self"><i class="fa-fw fas fa-wifi"></i><span> 朋友圈</span></a></li><li><a class="site-page" href="/link/" target="_self"><i class="fa-fw fas fa-link"></i><span> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-laptop-code"></i><span> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/sponsorWall/" target="_self"><i class="fa-fw fa-fw fas fa-money-check-alt"></i><span> 赞助墙</span></a></li><li><a class="site-page" href="/website/log" target="_self"><i class="fa-fw fas fa-file-medical-alt"></i><span> 日志墙</span></a></li><li><a class="site-page" href="/demandWall/" target="_self"><i class="fa-fw fa fa-bug"></i><span> 需求墙</span></a></li><li><a class="site-page" href="/policy/" target="_blank"><i class="fa-fw fa fa-fw fa-universal-access"></i><span> 隐私墙</span></a></li><li><a class="site-page" href="/@3.7.1/" target="_blank"><i class="fa-fw fa-fw fas fa-th-list"></i><span> 旧版本</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-user-secret"></i><span> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/about/" target="_self"><i class="fa-fw fas fa-heart"></i><span> 关于自己</span></a></li><li><a class="site-page" href="/nav/index.html" target="_blank"><i class="fa-fw fa-fw fas fa-infinity"></i><span> 网址收藏</span></a></li><li><a class="site-page" href="/music/index.html" target="_blank"><i class="fa-fw fa-fw fas fa-music"></i><span> 音乐长廊</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://bu.dusays.com/2021/03/06/31162e0f3b406.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="唐志远の博客"><span class="site-name">唐志远の博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/" target="_self"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-book"></i><span> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/archives/" target="_self"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page" href="/tags/" target="_self"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page" href="/categories/" target="_self"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/gallery/" target="_self"><i class="fa-fw fas fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page" href="/bangumis/" target="_self"><i class="fa-fw fab fa-youtube"></i><span> 番剧</span></a></li><li><a class="site-page" href="/movies/" target="_self"><i class="fa-fw fa-fw fas fa-clapperboard"></i><span> 电影</span></a></li><li><a class="site-page" href="/books/" target="_self"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page" href="/specialEffects/" target="_self"><i class="fa-fw fa fa-ship"></i><span> 特效</span></a></li><li><a class="site-page" href="/@3.7.1/wallpaper/" target="_blank"><i class="fa-fw fa-fw fas fa-images"></i><span> 壁纸</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-user-group"></i><span> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/comments/" target="_self"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></li><li><a class="site-page" href="/frdcenter/" target="_self"><i class="fa-fw fas fa-wifi"></i><span> 朋友圈</span></a></li><li><a class="site-page" href="/link/" target="_self"><i class="fa-fw fas fa-link"></i><span> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-laptop-code"></i><span> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/sponsorWall/" target="_self"><i class="fa-fw fa-fw fas fa-money-check-alt"></i><span> 赞助墙</span></a></li><li><a class="site-page" href="/website/log" target="_self"><i class="fa-fw fas fa-file-medical-alt"></i><span> 日志墙</span></a></li><li><a class="site-page" href="/demandWall/" target="_self"><i class="fa-fw fa fa-bug"></i><span> 需求墙</span></a></li><li><a class="site-page" href="/policy/" target="_blank"><i class="fa-fw fa fa-fw fa-universal-access"></i><span> 隐私墙</span></a></li><li><a class="site-page" href="/@3.7.1/" target="_blank"><i class="fa-fw fa-fw fas fa-th-list"></i><span> 旧版本</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-user-secret"></i><span> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/about/" target="_self"><i class="fa-fw fas fa-heart"></i><span> 关于自己</span></a></li><li><a class="site-page" href="/nav/index.html" target="_blank"><i class="fa-fw fa-fw fas fa-infinity"></i><span> 网址收藏</span></a></li><li><a class="site-page" href="/music/index.html" target="_blank"><i class="fa-fw fa-fw fas fa-music"></i><span> 音乐长廊</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">uni-app中websocket的使用 断开重连、心跳机制</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-09-10T11:51:31.000Z" title="发表于 2021-09-10 19:51:31">2021-09-10</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-05-17T10:01:12.000Z" title="更新于 2023-05-17 18:01:12">2023-05-17</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/uni-app/">uni-app</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1530</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="uni-app中websocket的使用 断开重连、心跳机制"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><div class="tip cogs faa-horizontal animated"><p>最近关于H5和APP的开发中使用到了webSocket，由于web&#x2F;app有时候会出现网络不稳定或者服务端主动断开，这时候导致消息推送不了的情况，需要客户端进行重连。查阅资料后发现了一个心跳机制，也就是客户端间隔一段时间就向服务器发送一条消息，如果服务器收到消息就回复一条信息过来，如果一定时间内没有回复，则表示已经与服务器断开连接了，这个时候就需要进行重连。</p>
<p>被动断开则进行重连，主动断开的不重连。</p>
</div>

<p>说明：下图针对两个Tab项（Open Trades 和 Closed Trades），只希望在 tabIndex &#x3D; 0 （Open Trades 高亮时）触发webSocket , 如果点击第二个栏目 , tabIndex &#x3D; 1（Closed Trades高亮时）则主动关闭webSodket连接。</p>
<p>TabIndex &#x3D; 0 时 ，被动断开则自动重连。</p>
<h1 id="效果"><a href="#效果" class="headerlink" title="效果"></a>效果</h1><ol>
<li>webScoket连接并接收推送的消息<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/214077a6000a1.jpg"/></div></div></li>
<li>将接收的消息转换成目标数据，并渲染<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/5678988bb155e.jpg"/></div></div></li>
<li>如果主动关闭，则不进行重连，监听关闭事件<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/97f43863d23b6.jpg"/></div></div></li>
<li>显示已关闭，不重连<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/6eee925c9f2dd.jpg"/></div></div></li>
<li>监听错误事件，比如地址，协议错误等，则会自动重连五次，五次重连仍失败后则需要进行手动重连<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/0a8fd12f2a4c4.jpg"/></div></div>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/d817f0ed5d7fb.jpg"/></div></div>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/8b6f83a0c771f.jpg"/></div></div></li>
<li>如果服务端主动断开，心跳机制会每隔一段时间发送一条数据给服务端，如果没有回复则会进行webScoket重连<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/ced1a2fddcf20.jpg"/></div></div>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2021/09/10/4c0191471d75a.jpg"/></div></div></li>
</ol>
<h1 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h1><ol>
<li>新建 socket.js ， 将以下代码复制进去 ，向外暴露。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> api <span class="keyword">from</span> <span class="string">&#x27;@/common/js/config.js&#x27;</span> <span class="comment">// 接口Api，图片地址等等配置，可根据自身情况引入，也可以直接在下面url填入你的 webSocket连接地址</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">socketIO</span> &#123;</span><br><span class="line">	<span class="title function_">constructor</span>(<span class="params">data, time, url</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">socketTask</span> = <span class="literal">null</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">is_open_socket</span> = <span class="literal">false</span> <span class="comment">//避免重复连接</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">url</span> = url ? url : api.<span class="property">websocketUrl</span>  <span class="comment">//连接地址</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">data</span> = data ? data : <span class="literal">null</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">connectNum</span> = <span class="number">1</span> <span class="comment">// 重连次数</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">traderDetailIndex</span> = <span class="number">100</span> <span class="comment">// traderDetailIndex ==2 重连</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">accountStateIndex</span> = <span class="number">100</span> <span class="comment">// accountStateIndex ==1 重连</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">followFlake</span> = <span class="literal">false</span> <span class="comment">// followFlake == true 重连</span></span><br><span class="line">		<span class="comment">//心跳检测</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">timeout</span> = time ? time : <span class="number">15000</span> <span class="comment">//多少秒执行检测</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">heartbeatInterval</span> = <span class="literal">null</span> <span class="comment">//检测服务器端是否还活着</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">reconnectTimeOut</span> = <span class="literal">null</span> <span class="comment">//重连之后多久再次重连</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 进入这个页面的时候创建websocket连接【整个页面随时使用】</span></span><br><span class="line">	<span class="title function_">connectSocketInit</span>(<span class="params">data</span>) &#123;</span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">data</span> = data</span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">socketTask</span> = uni.<span class="title function_">connectSocket</span>(&#123;</span><br><span class="line">			<span class="attr">url</span>: <span class="variable language_">this</span>.<span class="property">url</span>,</span><br><span class="line">			<span class="attr">success</span>: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">				<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;正准备建立websocket中...&quot;</span>);</span><br><span class="line">				<span class="comment">// 返回实例</span></span><br><span class="line">				<span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">socketTask</span></span><br><span class="line">			&#125;,</span><br><span class="line">		&#125;);</span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">socketTask</span>.<span class="title function_">onOpen</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">connectNum</span> = <span class="number">1</span></span><br><span class="line">			<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;WebSocket连接正常！&quot;</span>);</span><br><span class="line">			<span class="variable language_">this</span>.<span class="title function_">send</span>(data)</span><br><span class="line">			<span class="built_in">clearInterval</span>(<span class="variable language_">this</span>.<span class="property">reconnectTimeOut</span>)</span><br><span class="line">			<span class="built_in">clearInterval</span>(<span class="variable language_">this</span>.<span class="property">heartbeatInterval</span>)</span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">is_open_socket</span> = <span class="literal">true</span>;</span><br><span class="line">			<span class="variable language_">this</span>.<span class="title function_">start</span>();</span><br><span class="line">			<span class="comment">// 注：只有连接正常打开中 ，才能正常收到消息</span></span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">socketTask</span>.<span class="title function_">onMessage</span>(<span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">				<span class="comment">// 字符串转json</span></span><br><span class="line">				<span class="keyword">let</span> res = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(e.<span class="property">data</span>);</span><br><span class="line">				<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;res----------&gt;&quot;</span>, res) <span class="comment">// 这里 查看 推送过来的消息</span></span><br><span class="line">				<span class="keyword">if</span> (res.<span class="property">data</span>) &#123;</span><br><span class="line">					uni.$emit(<span class="string">&#x27;getPositonsOrder&#x27;</span>, res); </span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;)</span><br><span class="line">		<span class="comment">// 监听连接失败，这里代码我注释掉的原因是因为如果服务器关闭后，和下面的onclose方法一起发起重连操作，这样会导致重复连接</span></span><br><span class="line">		uni.<span class="title function_">onSocketError</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">			<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;WebSocket连接打开失败，请检查！&#x27;</span>);</span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">socketTask</span> = <span class="literal">null</span></span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">is_open_socket</span> = <span class="literal">false</span>;</span><br><span class="line">			<span class="built_in">clearInterval</span>(<span class="variable language_">this</span>.<span class="property">heartbeatInterval</span>)</span><br><span class="line">			<span class="built_in">clearInterval</span>(<span class="variable language_">this</span>.<span class="property">reconnectTimeOut</span>)</span><br><span class="line">			uni.$off(<span class="string">&#x27;getPositonsOrder&#x27;</span>)</span><br><span class="line">			<span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">connectNum</span> &lt; <span class="number">6</span>) &#123;</span><br><span class="line">				uni.<span class="title function_">showToast</span>(&#123;</span><br><span class="line">					<span class="attr">title</span>: <span class="string">`WebSocket连接失败，正尝试第<span class="subst">$&#123;<span class="variable language_">this</span>.connectNum&#125;</span>次连接`</span>,</span><br><span class="line">					<span class="attr">icon</span>: <span class="string">&quot;none&quot;</span></span><br><span class="line">				&#125;)</span><br><span class="line">				<span class="variable language_">this</span>.<span class="title function_">reconnect</span>();</span><br><span class="line">				<span class="variable language_">this</span>.<span class="property">connectNum</span> += <span class="number">1</span></span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				uni.$emit(<span class="string">&#x27;connectError&#x27;</span>);</span><br><span class="line">				<span class="variable language_">this</span>.<span class="property">connectNum</span> = <span class="number">1</span></span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">		&#125;);</span><br><span class="line">		<span class="comment">// 这里仅是事件监听【如果socket关闭了会执行】</span></span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">socketTask</span>.<span class="title function_">onClose</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">			<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;已经被关闭了-------&quot;</span>)</span><br><span class="line">			<span class="built_in">clearInterval</span>(<span class="variable language_">this</span>.<span class="property">heartbeatInterval</span>)</span><br><span class="line">			<span class="built_in">clearInterval</span>(<span class="variable language_">this</span>.<span class="property">reconnectTimeOut</span>)</span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">is_open_socket</span> = <span class="literal">false</span>;</span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">socketTask</span> = <span class="literal">null</span></span><br><span class="line">			uni.$off(<span class="string">&#x27;getPositonsOrder&#x27;</span>)</span><br><span class="line">			<span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">connectNum</span> &lt; <span class="number">6</span>) &#123;</span><br><span class="line">				<span class="variable language_">this</span>.<span class="title function_">reconnect</span>();</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				uni.$emit(<span class="string">&#x27;connectError&#x27;</span>);</span><br><span class="line">				<span class="variable language_">this</span>.<span class="property">connectNum</span> = <span class="number">1</span></span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">		&#125;)</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="comment">// 主动关闭socket连接</span></span><br><span class="line">	<span class="title class_">Close</span>() &#123;</span><br><span class="line">		<span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">is_open_socket</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">socketTask</span>.<span class="title function_">close</span>(&#123;</span><br><span class="line">			<span class="title function_">success</span>(<span class="params"></span>) &#123;</span><br><span class="line">				uni.<span class="title function_">showToast</span>(&#123;</span><br><span class="line">					<span class="attr">title</span>: <span class="string">&#x27;SocketTask 关闭成功&#x27;</span>,</span><br><span class="line">					<span class="attr">icon</span>: <span class="string">&quot;none&quot;</span></span><br><span class="line">				&#125;);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//发送消息</span></span><br><span class="line">	<span class="title function_">send</span>(<span class="params">data</span>) &#123;</span><br><span class="line">		<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;data----------&gt;&quot;</span>, data);</span><br><span class="line">		<span class="comment">// 注：只有连接正常打开中 ，才能正常成功发送消息</span></span><br><span class="line">		<span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">socketTask</span>) &#123;</span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">socketTask</span>.<span class="title function_">send</span>(&#123;</span><br><span class="line">				<span class="attr">data</span>: <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(data),</span><br><span class="line">				<span class="keyword">async</span> <span class="title function_">success</span>(<span class="params"></span>) &#123;</span><br><span class="line">					<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;消息发送成功&quot;</span>);</span><br><span class="line">				&#125;,</span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//开启心跳检测</span></span><br><span class="line">	<span class="title function_">start</span>(<span class="params"></span>) &#123;</span><br><span class="line">		<span class="variable language_">this</span>.<span class="property">heartbeatInterval</span> = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">			<span class="variable language_">this</span>.<span class="title function_">send</span>(&#123;</span><br><span class="line">				<span class="string">&quot;traderid&quot;</span>: <span class="number">10260</span>,</span><br><span class="line">				<span class="string">&quot;type&quot;</span>: <span class="string">&quot;Ping&quot;</span></span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;, <span class="variable language_">this</span>.<span class="property">timeout</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//重新连接</span></span><br><span class="line">	<span class="title function_">reconnect</span>(<span class="params"></span>) &#123;</span><br><span class="line">		<span class="comment">//停止发送心跳</span></span><br><span class="line">		<span class="built_in">clearInterval</span>(<span class="variable language_">this</span>.<span class="property">heartbeatInterval</span>)</span><br><span class="line">		<span class="comment">//如果不是人为关闭的话，进行重连</span></span><br><span class="line">		<span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">is_open_socket</span> &amp;&amp; (<span class="variable language_">this</span>.<span class="property">traderDetailIndex</span> == <span class="number">2</span> || <span class="variable language_">this</span>.<span class="property">accountStateIndex</span> == <span class="number">0</span> || <span class="variable language_">this</span></span><br><span class="line">			.<span class="property">followFlake</span>)) &#123;</span><br><span class="line">			<span class="variable language_">this</span>.<span class="property">reconnectTimeOut</span> = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">				<span class="variable language_">this</span>.<span class="title function_">connectSocketInit</span>(<span class="variable language_">this</span>.<span class="property">data</span>);</span><br><span class="line">			&#125;, <span class="number">5000</span>)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@description</span> 将 scoket 数据进行过滤 </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> &#123;<span class="type">array</span>&#125; <span class="variable">array</span></span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> &#123;<span class="type">string</span>&#125; type 区分 弹窗 openposition 分为跟随和我的</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="title function_">arrayFilter</span>(<span class="params">array, type = <span class="string">&#x27;normal&#x27;</span>, signalId = <span class="number">0</span></span>) &#123;</span><br><span class="line">		<span class="keyword">let</span> arr1 = []</span><br><span class="line">		<span class="keyword">let</span> arr2 = []</span><br><span class="line">		<span class="keyword">let</span> obj = &#123;</span><br><span class="line">			<span class="attr">arr1</span>: [],</span><br><span class="line">			<span class="attr">arr2</span>: []</span><br><span class="line">		&#125;</span><br><span class="line">		arr1 = array.<span class="title function_">filter</span>(<span class="function"><span class="params">v</span> =&gt;</span> v.<span class="property">flwsig</span> == <span class="literal">true</span>)</span><br><span class="line">		arr2 = array.<span class="title function_">filter</span>(<span class="function"><span class="params">v</span> =&gt;</span> v.<span class="property">flwsig</span> == <span class="literal">false</span>)</span><br><span class="line">		<span class="keyword">if</span> (type == <span class="string">&#x27;normal&#x27;</span>) &#123;</span><br><span class="line">			<span class="keyword">if</span> (signalId) &#123;</span><br><span class="line">				arr1 = array.<span class="title function_">filter</span>(<span class="function"><span class="params">v</span> =&gt;</span> v.<span class="property">flwsig</span> == <span class="literal">true</span> &amp;&amp; v.<span class="property">sigtraderid</span> == signalId)</span><br><span class="line">				<span class="keyword">return</span> arr1</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				<span class="keyword">return</span> arr1.<span class="title function_">concat</span>(arr2)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">if</span> (signalId &gt; <span class="number">0</span>) &#123;</span><br><span class="line">				arr1 = array.<span class="title function_">filter</span>(<span class="function"><span class="params">v</span> =&gt;</span> v.<span class="property">flwsig</span> == <span class="literal">true</span> &amp;&amp; v.<span class="property">sigtraderid</span> == signalId)</span><br><span class="line">				obj.<span class="property">arr1</span> = arr1</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				obj.<span class="property">arr1</span> = arr1</span><br><span class="line">			&#125;</span><br><span class="line">			obj.<span class="property">arr2</span> = arr2</span><br><span class="line">			</span><br><span class="line">			<span class="keyword">return</span> obj</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = socketIO</span><br></pre></td></tr></table></figure></li>
<li>在入口文件中 将 socketIO 挂载在 Vue 原型上 ， 也可以按需引入置顶页面 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> socketIO <span class="keyword">from</span> <span class="string">&#x27;@/common/js/scoket.js&#x27;</span></span><br><span class="line"><span class="title class_">Vue</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">socketIo</span> = <span class="keyword">new</span> <span class="title function_">socketIO</span>()</span><br></pre></td></tr></table></figure></li>
<li>在需要用到webSocket的页面中使用如下方法（可根据自身业务需求进行整改）<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">scoketClose</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">socketIo</span>.<span class="property">connectNum</span> = <span class="number">1</span></span><br><span class="line">    <span class="keyword">const</span> data = &#123;</span><br><span class="line">        <span class="string">&quot;value1&quot;</span>: <span class="string">&quot;demo1&quot;</span></span><br><span class="line">        <span class="string">&quot;value2&quot;</span>: <span class="string">&quot;demo2&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">socketIo</span>.<span class="title function_">send</span>(data) <span class="comment">// 这是给后端发送特定数据 关闭推送</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">socketIo</span>.<span class="title class_">Close</span>() <span class="comment">// 主动 关闭连接 ， 不会重连</span></span><br><span class="line">&#125;,</span><br><span class="line"></span><br><span class="line"><span class="title function_">getWebsocketData</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// 要发送的数据包</span></span><br><span class="line">    <span class="keyword">const</span> data = &#123;</span><br><span class="line">        <span class="string">&quot;value&quot;</span>: <span class="string">&quot;value1&quot;</span>,</span><br><span class="line">        <span class="string">&quot;type&quot;</span>: <span class="string">&quot;type1&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 打开连接</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">socketIo</span>.<span class="title function_">connectSocketInit</span>(data)</span><br><span class="line">    <span class="comment">// 接收数据</span></span><br><span class="line">    uni.$on(<span class="string">&quot;getPositonsOrder&quot;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">connect</span> = <span class="literal">true</span></span><br><span class="line">        <span class="keyword">const</span> &#123;</span><br><span class="line">            <span class="title class_">Code</span>,</span><br><span class="line">            data</span><br><span class="line">        &#125; = res</span><br><span class="line">        <span class="keyword">if</span> (<span class="title class_">Code</span> == xxxx) &#123;</span><br><span class="line">            <span class="comment">// 根据后端传过来的数据进行 业务编写。。。</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">           </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="comment">// 错误时做些什么</span></span><br><span class="line">    uni.$on(<span class="string">&quot;connectError&quot;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">connect</span> = <span class="literal">false</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">scoketError</span> = <span class="literal">true</span></span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>离开页面，记得断开连接。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">onUnload</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">scoketClose</span>()</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">socketIo</span>.<span class="property">traderDetailIndex</span> = <span class="number">100</span> <span class="comment">// 初始化 tabIndex </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>
<h1 id="遇到问题"><a href="#遇到问题" class="headerlink" title="遇到问题"></a>遇到问题</h1><div class="tip faa-horizontal"><p>如果在使用中遇到什么问题  ，可以给我留言 ，看到留言后会在第一时间进行回复 。</p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://fe32.top">Ethan.Tzy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://fe32.top/articles/soc145ket/">https://fe32.top/articles/soc145ket/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://fe32.top" target="_blank">唐志远の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/uni-app/">uni-app</a><a class="post-meta__tags" href="/tags/webSocket/">webSocket</a></div><div class="post_share"><div class="social-share" data-image="https://bu.dusays.com/2022/05/01/626e8da952344.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://npm.elemecdn.com/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://bu.dusays.com/2022/05/17/6283c3f127558.jpg" target="_blank"><img class="post-qr-code-img" src="https://bu.dusays.com/2022/05/17/6283c3f127558.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://bu.dusays.com/2022/05/17/6283c3ee6d872.jpg" target="_blank"><img class="post-qr-code-img" src="https://bu.dusays.com/2022/05/17/6283c3ee6d872.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><div class="ads-wrap"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9697737937582017" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block; text-align:center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-9697737937582017" data-ad-slot="6053380562"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/articles/reg384nt/" title="正则大全"><img class="cover" src="https://bu.dusays.com/2022/05/02/626eb247ad68f.png" onerror="onerror=null;src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">正则大全</div></div></a></div><div class="next-post pull-right"><a href="/articles/np2021sm/" title="CSS 实现新拟态(Neumorphism) UI 风格"><img class="cover" src="https://bu.dusays.com/2022/05/01/626e91194b2bb.png" onerror="onerror=null;src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">CSS 实现新拟态(Neumorphism) UI 风格</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/articles/uni10089/" title="uni-app 如何实现消息推送功能？"><img class="cover" src="https://bu.dusays.com/2022/12/04/638caada75585.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-12</div><div class="title">uni-app 如何实现消息推送功能？</div></div></a></div><div><a href="/articles/uni10088/" title="uni-app 提交 app应用 到 Google Play 提示 API 级别过低的解决办法"><img class="cover" src="https://bu.dusays.com/2023/01/05/63b6bcddb26d2.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-05</div><div class="title">uni-app 提交 app应用 到 Google Play 提示 API 级别过低的解决办法</div></div></a></div><div><a href="/articles/uni10087/" title="uni-app 整包更新与热更新方案(安卓和IOS)"><img class="cover" src="https://bu.dusays.com/2022/11/27/638365f6e62b2.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-11-27</div><div class="title">uni-app 整包更新与热更新方案(安卓和IOS)</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" onerror="this.onerror=null;this.src='https://bu.dusays.com/2021/03/27/0106da541a922.gif'" alt="avatar"/></div><div class="author-info__name">Ethan.Tzy</div><div class="author-info__description">2023年的理想开始实现了吗？</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">116</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">88</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><div class="card-info-social-icons is-center"><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2938526863&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://bu.dusays.com/2022/05/17/6283c39fcfc2f.png" target="_blank" title="Wechat"><i class="fab fa-weixin"></i></a><a class="social-icon" href="mailto:ethan4116@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://github.com/tzy13755126023" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://space.bilibili.com/481293298" target="_blank" title="Bilibili"><i class="fab fa-youtube"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="Rss"><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"><div style='text-indent:2em'>如果阅读过程中遇到了问题，请及时评论或者留言，看到了会在第一时间给出回复。</div><div id="qq-btn"><a id="a-qun" href="https://qm.qq.com/cgi-bin/qm/qr?k=IqfyAyFpCIMln6xPXkjkI_gzF8zx29zK&jump_from=webapi&authKey=jcME5f+e8XES0vAaUTAaI24tsgUMdoIZ0oGwAOoHNpK1HSWdcI9zmSlWVdfw/ax+" target="_blank">加入QQ群 ✨</a></div></div></div><div class="card-widget tzy-right-widget" id="card-wechat"><div id="flip-wrapper"><div id="flip-content"><div class="face"></div><div class="back face"></div></div></div></div><div class="card-widget tzy-ad-swiper"><div class="swiper card-swiper"><div class="swiper-wrapper"><div class="swiper-slide"><a href="https://fe32.top/sponsorWall/" target="_blank"><img src="https://bu.dusays.com/2023/03/29/642449cacc868.png"/></a></div><div class="swiper-slide"><a href="https://fe32.top/@3.7.1/" target="_blank"><img src="https://bu.dusays.com/2023/03/29/6424524c0d728.png"/></a></div></div><div class="swiper-pagination"></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%95%88%E6%9E%9C"><span class="toc-number">2.</span> <span class="toc-text">效果</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81"><span class="toc-number">3.</span> <span class="toc-text">代码</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%81%87%E5%88%B0%E9%97%AE%E9%A2%98"><span class="toc-number">4.</span> <span class="toc-text">遇到问题</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/articles/vue20006/" title="解决 Vue3 + Element Plus 树形表格全选多选以及子节点勾选的问题"><img src="https://bu.dusays.com/2023/10/23/65361d5beba7d.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="解决 Vue3 + Element Plus 树形表格全选多选以及子节点勾选的问题"/></a><div class="content"><a class="title" href="/articles/vue20006/" title="解决 Vue3 + Element Plus 树形表格全选多选以及子节点勾选的问题">解决 Vue3 + Element Plus 树形表格全选多选以及子节点勾选的问题</a><time datetime="2023-10-23T07:02:24.000Z" title="发表于 2023-10-23 15:02:24">2023-10-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/articles/fe100003/" title="前端断点调试是如何实现的？"><img src="https://bu.dusays.com/2023/10/21/65338be5ce691.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="前端断点调试是如何实现的？"/></a><div class="content"><a class="title" href="/articles/fe100003/" title="前端断点调试是如何实现的？">前端断点调试是如何实现的？</a><time datetime="2023-10-23T01:01:11.000Z" title="发表于 2023-10-23 09:01:11">2023-10-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/articles/skill001/" title="几个非常实用的 Chrome Devtools 技巧"><img src="https://bu.dusays.com/2023/10/17/652e3c79ec949.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="几个非常实用的 Chrome Devtools 技巧"/></a><div class="content"><a class="title" href="/articles/skill001/" title="几个非常实用的 Chrome Devtools 技巧">几个非常实用的 Chrome Devtools 技巧</a><time datetime="2023-10-17T07:53:32.000Z" title="发表于 2023-10-17 15:53:32">2023-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/articles/fe100002/" title="卷王之王：快来看看前端出的新框架！"><img src="https://bu.dusays.com/2023/10/16/652ce0f2b059c.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="卷王之王：快来看看前端出的新框架！"/></a><div class="content"><a class="title" href="/articles/fe100002/" title="卷王之王：快来看看前端出的新框架！">卷王之王：快来看看前端出的新框架！</a><time datetime="2023-10-17T04:57:45.000Z" title="发表于 2023-10-17 12:57:45">2023-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/articles/fe100001/" title="前端如何实现埋点上报？"><img src="https://bu.dusays.com/2023/09/14/6502add885468.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="前端如何实现埋点上报？"/></a><div class="content"><a class="title" href="/articles/fe100001/" title="前端如何实现埋点上报？">前端如何实现埋点上报？</a><time datetime="2023-09-15T12:55:32.000Z" title="发表于 2023-09-15 20:55:32">2023-09-15</time></div></div></div></div><div class="card-widget ads-wrap"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9697737937582017" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-9697737937582017" data-ad-slot="9637402350" data-ad-format="auto" data-full-width-responsive="true"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div></div></div></main><footer id="footer"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">公益广告</p><div class="bg-ad"><div>国家反诈中心是国务院打击治理电信网络新型违法犯罪工作部际联席会议合成作战平台，集资源整合、情报研判、侦查指挥为一体，在打击、防范、治理电信网络诈骗等新型违法犯罪中发挥着重要作用。</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://www.hack-gov.com.cn/posts/21480.html">下载（国家反诈中心） APP</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">修仙导航</p><ul class="ft-links"><li><a href="https://fe32.top/articles/hexo1600/">建站指南</a><a href="https://fe32.top/nav.html">网址导航</a></li><li><a href="https://fe32.top/sponsorWall/">来杯咖啡</a><a href="https://fe32.top/comments/">留点什么</a></li><li><a href="https://fe32.top/about/">关于博主</a><a href="https://fe32.top/archives/">文章归档</a></li><li><a href="https://fe32.top/categories/">文章分类</a><a href="https://fe32.top/tags/">文章标签</a></li><li><a href="https://fe32.top/gallery/">我的相册</a><a href="https://fe32.top/bangumis/">我的追番</a></li><li><a href="https://fe32.top/specialEffects/">一些特效</a><a href="https://fe32.top/website/log/">更新日志</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链</p><div class="ft-img-group"><div class="img-group-item"><a href="https://fe32.top/"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://blog.zhheo.com/"><img src="https://npm.elemecdn.com/guli-heo/img/avatar2.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.thyuu.com/"><img src="https://npm.elemecdn.com/imgscdn/img/202111191951780.JPG" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://dusays.com/"><img src="https://cdn.dusays.com/avatar.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://akilar.top/"><img src="https://npm.elemecdn.com/akilar-candyassets/image/siteicon/favicon.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.fomal.cc/"><img src="https://bu.dusays.com/2022/11/06/6367af8667f0e.webp" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.startly.cn/"><img src="https://bu.dusays.com/2023/04/15/643a99cb740a4.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:btf.snackbarShow(&quot;预留友链位~~&quot;)"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""/></a></div></div></div></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/utils.js"></script><script src="/js/main.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/fancybox.umd.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/lazyload.iife.min.js"></script><script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.js"></script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo.fe32.top',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'https://twikoo.fe32.top',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    GLOBAL_CONFIG_SITE.isPost && getCount()
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'https://twikoo.fe32.top',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-volume="0.4" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer src="/js/swiper-bundle.js"></script><script defer src="/js/custom/index.js"></script><script> var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "https://hm.baidu.com/hm.js?1773f8575623b779a23176908895ed29";var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s);})();</script><script>!function(p){"use strict";!function(t){var s=window,e=document,i=p,c="".concat("https:"===e.location.protocol?"https://":"http://","sdk.51.la/js-sdk-pro.min.js"),n=e.createElement("script"),r=e.getElementsByTagName("script")[0];n.type="text/javascript",n.setAttribute("charset","UTF-8"),n.async=!0,n.src=c,n.id="LA_COLLECT",i.d=n;var o=function(){s.LA.ids.push(i)};s.LA?s.LA.ids&&o():(s.LA=p,s.LA.ids=[],o()),r.parentNode.insertBefore(n,r)}()}({id:"Jo9JJAc5cBaxwwnJ",ck:"Jo9JJAc5cBaxwwnJ"});</script><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9697737937582017" crossorigin="anonymous"></script><script src="https://npm.elemecdn.com/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><link rel="stylesheet" href="https://npm.elemecdn.com/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/aplayer/dist/APlayer.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/meting.min.js"></script><script src="https://npm.elemecdn.com/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"]):not([href="/books/"]):not([href="/movies/"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div></div></div><div id="algolia-tips"><span class="algolia-tips-text">Algolia 提供搜索服务</span></div></div></div><div id="search-mask"></div><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/algoliasearch.umd.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/instantsearch.production.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@4.7.0/js/algolia@latest.js"></script></div><!-- hexo injector body_end start --><script async src="//at.alicdn.com/t/font_2315348_g8vs01iykv.js"></script><!-- hexo injector body_end end --></body></html>